<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Description of Transaksi
 *
 * @author Hadi
 */
class transaksi extends Admin_My_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->model('transaksi/model_transaksi');
        $this->load->helper('transaksi');
    }

    /**
     * QUOTATION
     */

    public function quotation($is_popup = 0) {
        $this->load->library("datagrid");

        $data = array();

        $this->log_event = "Membuka menu quotation";

        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("q.nomor_quotation", "q.subject", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Quotation", "Subjek", "To", "Nama Vessel");
        $field_type = array("text", "text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/quotation", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(q.tanggal_quotation) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $offset = $this->input->get("per_page") ? $this->input->get("per_page") : 0;
        $length = 30;
        $result = $this->model_transaksi->getQuotationData($where, $offset, $length);
        $rowCount = $result->num_rows();

        if(!$is_popup) {
            $this->datagrid->setActionColumnsWidth(50);
            $this->datagrid->addMenu(GreyBox::createLink(base_url() . "index.php/transaksi/quotation_add/", "", "Tambah Data", "add", "onclick", 1024, 600));
            $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/quotation_export/?" . $this->input->server("QUERY_STRING") . "\" class=\"report\" title=\"Export Data Quotation\">&nbsp;</a>");
        }
        else {
            $this->datagrid->setActionColumnVisible(false);
        }
        $this->datagrid->setColumns("No.", "Nomor Quotation", "Tanggal", "To", "Subject", "No RF", "Nama Vessel", "Submitter");
        $this->datagrid->setPaginationDataNew($this->model_transaksi->get_scalar("SELECT COUNT(*) as jml FROM data_quotation_to_cust q $where", "jml"), $length, "transaksi/quotation", $rowCount, $offset);
        $this->datagrid->setButtonExportVisible(false);

        if ($rowCount > 0) {
            $nomor = $offset + 1;

            foreach ($result->result() as $row) {
                $rowID = $row->id_quotation;
                if(!$is_popup) {
                    $this->datagrid->addRowAction("edit('" . $rowID . "')", "edit", "Ubah Quotation");
                    $this->datagrid->addRowAction("cetak('" . $rowID . "')", "resume", "Cetak Quotation");
                    $this->datagrid->addRowAction("hapus('" . $rowID . "')", "delete", "Hapus Quotation");
                } else {
                    $this->datagrid->onRowClickAction("parent.parent._obj_fSendValue('" . $rowID . "')");
                }

                $this->datagrid->addRowData(
                        $nomor++, $row->nomor_quotation, $row->tanggal_quotation, $row->nama_customer, $row->subject, $row->rf_number, $row->nama_vessel, $row->submitter
                );
            }
        }
        else {
            $this->datagrid->setEmptyDataState("Tidak ada data");
        }

        $data['date_picker'] = new jDatePicker();
        $data['filter_panel'] = $filter_panel;

        if(!$is_popup) {
            $data['breadcrumb'] = $this->breadCrumb(true);
            $this->loadMenu('transaksi/quotation', $data);
        } else
            $this->loadMenuHeaderPopup('transaksi/quotation', $data);
    }

    public function quotation_add($kode) {
        $data = array();

        if($this->input->post("btnSubmit")) {
            $vars = array(
                    "nama_customer" => "",
                    "id_customer" => "",
                    "tanggal_quotation" => date("Y-m-d"),
                    "alamat_detail_customer" => "",
                    "nomor_quotation" => "",
                    "rf_number" => "",
                    "alamat_komplit" => "",
                    "kontak_komplit" => "",
                    "nama_vessel" => "",
                    "id_vessel" => "",
                    "attendance" => "",
                    "nama_port" => "",
                    "id_port" => "",
                    "subject" => "",
                    "crc" => "IDR",
                    "ppn" => 0,
                    "diskon" => 0,
                    "termcondition" => 1,
                    "approved_by" => "",
                    "quote_by" => $this->userauth->getNickName(),
                    "btnSubmit" => "Save",
                    "id_item" => array(),
                    "nama_item" => array(),
                    "quantity" => array(),
                    "harga_beli" => array(),
                    "harga_jual" => array(),
                    "harga_beli_dollar" => array(),
                    "harga_jual_dollar" => array(),
                    "satuan" => array()
            );

            $data = array();
            retrieve_request($data, $vars);
            $data["submitter"] = $this->userauth->getNik();
            $data["date_submit"] = date("Y-m-d H:i:s");
            $data["using_dollar_currency"] = $data["crc"] == "USD" ? 1 : 0;

            if(count($data["id_item"]) < 1)
                $data["error"] = "Item can't be empty";
            else {
                if(empty($data["id_customer"]))
                    $data["id_customer"] = $this->model_transaksi->insertCustomer($data);
                if(empty($data["id_vessel"]))
                    $data["id_vessel"] = $this->model_transaksi->insertVessel($data);
                if(empty($data["id_port"]))
                    $data["id_port"] = $this->model_transaksi->insertPort($data);

                if($kode == "")
                    $id_quot = $this->model_transaksi->insertQuotation($data);
                else {
                    $id_quot = $kode;
                    $this->model_transaksi->updateQuotation($data, $id_quot);
                }

                $this->model_transaksi->db->delete("data_quotation_to_cust_item", "id_quotation = '$id_quot'");
                $i=0;
                foreach($data["id_item"] as $key => $id) {
                    $varData = array(
                            "id_quotation" => $id_quot,
                            "id_item" => $key,
                            "nama_item"=> $data["nama_item"][$i],
                            "satuan_beli"=> $data["satuan"][$i],
                            "quantity" => $data["quantity"][$i],
                            "harga_beli" => $data["harga_beli"][$i],
                            "harga_jual" => $data["harga_jual"][$i],
                            "harga_beli_dollar" => $data["harga_beli_dollar"][$i],
                            "harga_jual_dollar" => $data["harga_jual_dollar"][$i]
                    );                    
                    $this->model_transaksi->insertQuotationItem($varData);
                    $i++;
                }

                $data["is_success"] = 1;
                $data["kode"] = $id_quot;
            }

            if(!$data["is_success"] && count($data["id_item"]) > 0) {
                $this->load->library("dbresult_dummy");

                foreach($data["id_item"] as $key => $id) {
                    $item = $this->model_transaksi->getItem($id);
                    $this->dbresult_dummy->new_object($item);
                    $this->dbresult_dummy->assoc("quantity", $data["quantity"][$key]);
                    $this->dbresult_dummy->insert_object();
                }

                $data["item"] = $this->dbresult_dummy;
            }
        }

        if($kode != "") {
            retrieve_quotation_data($data, $kode);
            $data["kode"] = $kode;
        }
        else {
            $data["tanggal_quotation"] = date("Y-m-d");
            $data["quote_by"] =$this->userauth->getNickName();
            $data["diskon"] = 0;
        }

        $query = $this->model_transaksi->getCustomerList();
        $queryTC = $this->model_transaksi->getTermConditionList();
        $prefix = $this->model_transaksi->getPrefixQuotationNo();
        $data["customerlist"] = $query->result();
        $data["termconditionlist"] = $queryTC->result();
        $data["prefix"]=$prefix;

        $data['gbcust'] = $this->greybox->createLink(base_url() . 'index.php/popup/customer', '<span></span>', 'Cari Customer', 'find', '', 750, 450);
        $data['gbvessel'] = $this->greybox->createLink(base_url() . 'index.php/popup/vessel', '<span></span>', 'Cari Vessel', 'find', '', 500, 450);
        $data['gbport'] = $this->greybox->createLink(base_url() . 'index.php/popup/port', '<span></span>', 'Cari Port', 'find', '', 750, 450);
        $data['gbitem'] = $this->greybox->createLink(base_url() . 'index.php/popup/item_finalisasi_dollar', '<span>Tambah Item</span>', 'Tambah Item', 'find', '', 1024, 450);
        
        $this->loadMenuHeaderPopup("transaksi/view_quotation_add",$data);
    }

    public function quotation_delete($kode) {
        $this->model_transaksi->deleteQuotation($kode);
        echo "<script>alert('Data berhasil dihapus');</script>";
        echo "<script>location.href = '".  site_url("transaksi/quotation?".$_SERVER["QUERY_STRING"])."'</script>";
    }

    public function quotation_print($kode = "") {
        $data = array();
        retrieve_quotation_data($data, $kode);

        $this->load->library("dcpdf");

        $obj_pdf = new dcpdf('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $obj_pdf->SetCreator(PDF_CREATOR);
        $title = "Data Quotation";
        $obj_pdf->SetTitle($title);
        if($data["use_header"]) {
            $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
            $obj_pdf->setFooterVisible(TRUE);
        }
        $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $obj_pdf->SetDefaultMonospacedFont('helvetica');
        $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $obj_pdf->SetFont('times', '', 10);
        $obj_pdf->setFontSubsetting(false);
        $obj_pdf->AddPage();
        $content = $this->load->view("transaksi/view_quotation_print", $data, true);
        $obj_pdf->writeHTML($content, true, false, true, false, '');
        $obj_pdf->Output('quotation-'.$kode.'.pdf', 'I');
    }

    public function quotation_export() {
        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("q.nomor_quotation", "q.subject", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Quotation", "Subjek", "To", "Nama Vessel");
        $field_type = array("text", "text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/quotation", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(q.tanggal_quotation) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $queryExport = "SELECT q.nomor_quotation, q.tanggal_quotation, q.rf_number, q.using_dollar_currency, q.using_ppn, q.approved_by, q.quote_by,
                q.submitter, q.date_submit, q.subject, c.nama_customer, c.kota_customer, c.alamat_customer, c.alamat_detail_customer, c.kode_pos_customer,
                c.telepon_customer, c.fax_customer, c.email_customer, c.attendance, v.nama_vessel, p.nama_port, t.nama_tc
                FROM data_quotation_to_cust q
                LEFT JOIN master_customer c ON q.id_customer = c.id_customer
                LEFT JOIN master_vessel v ON q.id_vessel = v.id_vessel 
                LEFT JOIN master_port p ON p.id_port = q.id_port
                LEFT JOIN master_term_condition t ON t.id_tc = q.id_tc
                $where";

        $this->export($queryExport);
    }


    /**
     * PURCHASING ORDER
     */

    public function purchase($is_popup = 0) {
        $this->load->library("datagrid");

        $data = array();

        $this->log_event = "Membuka menu purchase";

        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("p.nomor_po", "p.subject", "c.nama_customer");
        $field_title = array("Nomor Purchase", "Subjek", "To");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/purchase", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(p.tanggal_po) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $offset = $this->input->get("per_page") ? $this->input->get("per_page") : 0;
        $length = 30;
        $result = $this->model_transaksi->getPurchaseData($where, $offset, $length);

        $rowCount = $result->num_rows();

        if(!$is_popup) {
            $this->datagrid->setActionColumnsWidth(50);
            $this->datagrid->addMenu(GreyBox::createLink(base_url() . "index.php/transaksi/purchase_add/", "", "Tambah Data", "add", "onclick", 1024, 600));
            $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/purchase_export/?" . $this->input->server("QUERY_STRING") . "\" class=\"report\" title=\"Export Data Purchase Order\">&nbsp;</a>");
        }
        else {
            $this->datagrid->setActionColumnVisible(false);
        }
        $this->datagrid->setColumns("No.", "Nomor PO", "Tanggal", "To", "Daftar Quotation", "Catatan", "Submitter");
        $this->datagrid->setPaginationDataNew($this->model_transaksi->get_scalar("SELECT COUNT(*) as jml FROM data_po_from_customer p $where", "jml"), $length, "transaksi/purchase", $rowCount, $offset);
        $this->datagrid->setButtonExportVisible(false);

        if ($rowCount > 0) {
            $nomor = $offset + 1;

            foreach ($result->result() as $row) {
                $rowID = $row->id_po;
                if($row->list_quotation_id != "")
                    $list_quotation = $this->model_transaksi->get_scalar("SELECT GROUP_CONCAT(nomor_quotation SEPARATOR ',') as ids FROM data_quotation_to_cust WHERE id_quotation IN ($row->list_quotation_id)", "ids");
                else
                    $list_quotation = "-";

                if(!$is_popup) {
                    $this->datagrid->addRowAction("edit('" . $rowID . "')", "edit", "Ubah Purchase");
                    $this->datagrid->addRowAction("cetak('" . $rowID . "')", "resume", "Cetak Purchase");
                    $this->datagrid->addRowAction("hapus('" . $rowID . "')", "delete", "Hapus Purchase");
                } else {
                    $this->datagrid->onRowClickAction("parent.parent._obj_fSendValue('" . $rowID . "')");
                }

                $this->datagrid->addRowData(
                        $nomor++, $row->nomor_po, $row->tanggal_po, $row->nama_customer, str_replace(",", "<br/>", $list_quotation), $row->catatan_po, $row->submitter
                );
            }
        }
        else {
            $this->datagrid->setEmptyDataState("Tidak ada data");
        }

        $data['date_picker'] = new jDatePicker();
        $data['filter_panel'] = $filter_panel;

        if(!$is_popup) {
            $data['breadcrumb'] = $this->breadCrumb(true);
            $this->loadMenu('transaksi/purchase', $data);
        } else {
            $this->loadMenuHeaderPopup('transaksi/purchase', $data);
        }
    }

     public function purchase_add($kode = "") {
        $data = array();

        if($this->input->post("btnSubmit")) {
            $vars = array(
                    "tanggal_po" => date("Y-m-d"),
                    "list_quotation_id" => "",
                    "catatan_po" => "",
                    "id_customer" => "",
                    "id_item" => array(),
                    "nama_item" => array(),
                    "quantity" => array(),
                    "harga_beli" => array(),
                    "harga_jual" => array(),
                    "harga_beli_dollar" => array(),
                    "harga_jual_dollar" => array(),
                    "satuan_beli" => array(),
                    "selected" => array(),
                    "crc" => "IDR",
                    "btnSubmit" => "Save",
                    "nama_customer" => "",
                    "alamat_detail_customer" => "",
                    "alamat_komplit" => "",
                    "kontak_komplit" => "",
                    "using_dollar_currency" => "",
                    "nomor_po" => "",
                    "diskon" => 0
            );

            $data = array();
            retrieve_request($data, $vars);
            $data["submitter"] = $this->userauth->getNik();
            $data["date_submit"] = date("Y-m-d H:i:s");
            $data["using_dollar_currency"] = $data["crc"] == "USD" ? 1 : 0;

            if($data["nama_customer"] == "" && $data["list_quotation_id"] == "")
                $data["error"] = "If list quotation ID is empty then Customer name can't be empty";
            else if(count($data["selected"]) <= 0)
                $data["error"] = "Item can't be empty";
            else {

                $upload_success = true;
                if($_FILES["file_upload"]["name"] != "") {
                    $config = array();

                    $dir = str_replace("system/", "", BASEPATH) . 'import/';

                    if (!is_dir($dir)) {
                        mkdir($dir, 777);
                    }

                    $config['upload_path'] = $dir;
                    $config['overwrite'] = true;
                    $config["allowed_types"] = "doc|docx|xls|xlsx|pdf|txt|rtf|csv|jpg|jpeg|bmp|png";
                    $config["file_name"] = "data_upload_po_" . date("dmYHis");

                    $this->load->library('upload', $config);

                    if (!$this->upload->do_upload("file_upload")) {
                        $data["error"] = $this->upload->display_errors();
                        $upload_success = false;
                    } else {
                        $data["upload_data"] = $this->upload->data();
                        $data["file_upload"] = $data["upload_data"]["file_name"];
                    }

                }

                if($upload_success) {
                    if(empty($data["id_customer"]))
                        $data["id_customer"] = $this->model_transaksi->insertCustomer($data);

                    if($kode == "")
                        $id_po = $this->model_transaksi->insertPurchase($data);
                    else {
                        $id_po = $kode;
                        $this->model_transaksi->updatePurchase($data, $id_po);
                    }

                    $this->model_transaksi->db->delete("data_po_from_customer_item", "id_po = '$id_po'");
                    foreach($data["id_item"] as $key => $id) {
                        if(in_array($id, $data["selected"]))
                            $this->model_transaksi->insertPurchaseItem($id_po, $key, $data);
                    }

                    $data["is_success"] = 1;
                    $data["kode"] = $id_po;
                }
            }

            if(!$data["is_success"] && count($data["id_item"]) > 0) {
                $this->load->library("dbresult_dummy");

                foreach($data["id_item"] as $key => $id) {
                    $item = $this->model_transaksi->getItem($id);
                    $this->dbresult_dummy->new_object($item);
                    $this->dbresult_dummy->assoc("quantity", $data["quantity"][$key]);
                    $this->dbresult_dummy->insert_object();
                }

                $data["item"] = $this->dbresult_dummy;
            }
        }

        if($kode != "") {
            retrieve_purchase_data($data, $kode);
            $data["kode"] = $kode;
        }
        else {
            $data["tanggal_po"] = date("Y-m-d");
            $data["diskon"] = 0;
        }

        $data["prefix"] = $this->model_transaksi->getPrefixPurchaseNo();
        $data['gbquote'] = $this->greybox->createLink(base_url() . 'index.php/popup/quotationlist', '<span></span>', 'Cari Data Quotation', 'find', '', 500, 450);
        $data['gbitem'] = $this->greybox->createLink(base_url() . 'index.php/popup/master_item', '<span>Tambah Item</span>', 'Tambah Item', 'find', '', 820, 450);

        $this->loadMenuHeaderPopup("transaksi/view_purchase_add",$data);
    }

    public function purchase_delete($kode) {
        $this->model_transaksi->deletePurchase($kode);
        echo "<script>alert('Data berhasil dihapus');</script>";
        echo "<script>location.href = '".  site_url("transaksi/purchase?".$_SERVER["QUERY_STRING"])."'</script>";
    }

    public function purchase_print($kode) {
        $data = array();
        retrieve_purchase_data($data, $kode);

        $this->load->library("dcpdf");

        $obj_pdf = new dcpdf('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $obj_pdf->SetCreator(PDF_CREATOR);
        $title = "Data Purchase Order";
        $obj_pdf->SetTitle($title);
        if($data["use_header"]) {
            $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
            $obj_pdf->setFooterVisible(TRUE);
        }
        $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $obj_pdf->SetDefaultMonospacedFont('helvetica');
        $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $obj_pdf->SetFont('times', '', 10);
        $obj_pdf->setFontSubsetting(false);
        $obj_pdf->AddPage();
        $content = $this->load->view("transaksi/view_purchase_print", $data, true);
        $obj_pdf->writeHTML($content, true, false, true, false, '');
        $obj_pdf->Output('po-'.$kode.'.pdf', 'I');
    }

    public function purchase_export() {
        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("p.nomor_po", "p.subject", "c.nama_customer");
        $field_title = array("Nomor Purchase", "Subjek", "To");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/purchase", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(p.date_po) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $queryExport = "SELECT p.tanggal_po, p.nomor_po, p.list_quotation_id, p.using_dollar_currency, p.id_customer,
                p.catatan_po, p.submitter, p.date_submit, c.nama_customer, c.kota_customer, c.alamat_customer, c.alamat_detail_customer, c.kode_pos_customer,
                c.telepon_customer, c.fax_customer, c.email_customer, c.attendance
                FROM data_po_from_customer p
                LEFT JOIN master_customer c ON p.id_customer = c.id_customer
                $where";

        $this->export($queryExport);
    }

    /**
     * PURCHASING ORDER
     */

    public function invoice($jenis_invoice = "") {
        $this->load->library("datagrid");

        $data = array();

        $this->log_event = "Membuka menu invoice";

        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("i.nomor_invoice", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Invoice", "To", "Nama Vessel");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/invoice", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(i.tanggal_invoice) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        
        if ($jenis_invoice != ""){
            $where .= " and i.is_final = ".$jenis_invoice;
        }
        
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $offset = $this->input->get("per_page") ? $this->input->get("per_page") : 0;
        $length = 30;
        $result = $this->model_transaksi->getInvoiceData($where, $offset, $length);

        $this->datagrid->addMenu(GreyBox::createLink(base_url() . "index.php/transaksi/invoice_add/", "", "Tambah Data", "add", "onclick", 1024, 600));
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/invoice_export/$jenis_invoice?" . $this->input->server("QUERY_STRING") . "\" class=\"report\" title=\"Export Data Invoice Order\">&nbsp;</a>");
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/invoice/1?" . $this->input->server("QUERY_STRING") . "\">Lunas</a>/");
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/invoice/0?" . $this->input->server("QUERY_STRING") . "\">Belum Lunas</a>/");
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/invoice/?" . $this->input->server("QUERY_STRING") . "\">Semua</a>");

        $rowCount = $result->num_rows();

        $this->datagrid->setActionColumnsWidth(50);
        $this->datagrid->setColumns("No.", "Nomor Invoice", "Tanggal", "To", "Daftar DN", "Catatan", "Submitter");
        $this->datagrid->setPaginationDataNew($this->model_transaksi->get_scalar("SELECT COUNT(*) as jml FROM data_invoice_to_cust i $where", "jml"), $length, "transaksi/invoice", $rowCount, $offset);
        $this->datagrid->setButtonExportVisible(false);

        if ($rowCount > 0) {
            $nomor = $offset + 1;

            foreach ($result->result() as $row) {
                $rowID = $row->id_invoice;
                if($row->list_dn_id != "")
                    $list_dn = $this->model_transaksi->get_scalar("SELECT GROUP_CONCAT(nomor_dn SEPARATOR ',') as ids FROM data_dn_to_cust WHERE id_dn IN ($row->list_dn_id)", "ids");
                else
                    $list_dn = "-";

                $this->datagrid->addRowAction("edit('" . $rowID . "')", "edit", "Ubah Invoice");
                $this->datagrid->addRowAction("cetak('" . $rowID . "')", "resume", "Cetak Invoice");
                $this->datagrid->addRowAction("hapus('" . $rowID . "')", "delete", "Hapus Invoice");
                if ($row->is_final == 0) {
                    $this->datagrid->addRowAction("finalisasi('" . $rowID . "')", "snapshot", "Finalisasi Invoice");
                    $this->datagrid->setRowStyle("GridItem2");
                } else {
                    $this->datagrid->setRowStyle("GridItem1");
                }
                $this->datagrid->addRowData(
                        $nomor++, $row->nomor_invoice, $row->tanggal_invoice, $row->nama_customer, str_replace(",", "<br/>", $list_dn), $row->penerbit_invoice, $row->submitter
                );
            }
        }
        else {
            $this->datagrid->setEmptyDataState("Tidak ada data");
        }

        $data['breadcrumb'] = $this->breadCrumb(true);
        $data['date_picker'] = new jDatePicker();
        $data['filter_panel'] = $filter_panel;

        $this->loadMenu('transaksi/invoice', $data);
    }

    public function invoice_add($kode = "") {
        $data = array();

        if($this->input->post("btnSubmit")) {
            $vars = array(
                    "nomor_invoice" => "",
                    "tanggal_invoice" => date("Y-m-d"),
                    "id_po" => "",
                    "ppn" => 0,
                    "crc" => "IDR",
                    "penerbit_invoice" => "",
                    "btnSubmit" => "Save",
                    "diskon_iv" => 0,
                    "temp_id_iv" => 0,
                    "id_item" => array(),
                    "nama_item" => array(),
                    "quantity" => array(),
                    "harga_beli" => array(),
                    "harga_jual" => array(),
                    "harga_beli_dollar" => array(),
                    "harga_jual_dollar" => array(),
                    "satuan" => array()
            );

            retrieve_request($data, $vars);            
            retrieve_purchase_data($data, $data["id_po"]);

            if($data["temp_id_iv"] == 0)
                $data["temp_id_iv"] = $this->model_transaksi->nextInvoiceVal();

            $data["submitter"] = $this->userauth->getNik();
            $data["date_submit"] = date("Y-m-d H:i:s");
            $data["using_dollar_currency"] = $data["crc"] == "USD" ? 1 : 0;
            $data["list_dn"] = $this->model_transaksi->getDeliveryData("WHERE d.id_invoice = ".$data["temp_id_iv"]);

            if($data["id_po"] == "")
                $data["error"] = "Purchase order number can't be empty";
            else {
                $list_id_dn = array();
                foreach($data["list_dn"]->result() as $row)
                    $list_id_dn[] = $row->id_dn;
                $data["list_dn_id"] = implode(",", $list_id_dn);

                if($kode == "")
                    $id_invoice = $this->model_transaksi->insertInvoice($data);
                else {
                    $id_invoice = $kode;
                    $this->model_transaksi->updateInvoice($data, $id_invoice);
                }

                $this->model_transaksi->db->delete("data_invoice_to_cust_item", "id_invoice = '$id_invoice'");
                $i = 0;
                foreach($data["id_item"] as $key) {
                    $varData = array(
                            "id_invoice" => $id_invoice,
                            "id_item" => $key,
                            "nama_item"=> $data["nama_item"][$i],
                            "satuan_beli"=> $data["satuan"][$i],
                            "quantity" => $data["quantity"][$i],
                            "harga_beli" => $data["harga_beli"][$i],
                            "harga_jual" => $data["harga_jual"][$i],
                            "harga_beli_dollar" => $data["harga_beli_dollar"][$i],
                            "harga_jual_dollar" => $data["harga_jual_dollar"][$i]
                    );                    
                    $this->model_transaksi->insertInvoiceItem($id_invoice, $varData);
                    $i++;
                }

                $data["is_success"] = 1;
                $data["kode"] = $id_invoice;
            }
        }

        if($kode != "") {
            $id_po = $this->input->get("po", true);
            retrieve_invoice_data($data, $kode, $id_po);            
            $data["kode"] = $kode;
            $data["temp_iv_id"] = $kode;
        } else {
            $id_po = $this->input->get("po", true);

            retrieve_purchase_data($data, $id_po);

            $data["diskon_iv"] = $data["diskon"];
            $data["tanggal_invoice"] = date("Y-m-d");
            $data["penerbit_invoice"] = $this->userauth->getNickName();

            $data["temp_iv_id"] = $this->model_transaksi->nextInvoiceVal();
        }

        $data['gbitemdollar'] = $this->greybox->createLink(base_url() . 'index.php/popup/item_finalisasi_dollar', '<span>Tambah Item</span>', 'Tambah Item', 'find', '', 1024, 450);
        $data["prefix"] = $this->model_transaksi->getPrefixInvoiceNo();
        $data['gbpo'] = $this->greybox->createLink(base_url() . 'index.php/transaksi/purchase/1', '<span></span>', 'Cari Data PO', 'find', '', 800, 480);

        $this->loadMenuHeaderPopup("transaksi/view_invoice_add",$data);
    }

    public function invoice_delete($kode) {
        $this->model_transaksi->deleteInvoice($kode);
        echo "<script>alert('Data berhasil dihapus');</script>";
        echo "<script>location.href = '".  site_url("transaksi/invoice?".$_SERVER["QUERY_STRING"])."'</script>";
    }

    public function invoice_print($kode) {
        $data = array();
        retrieve_invoice_data($data, $kode);

        $this->load->library("dcpdf");

        $obj_pdf = new dcpdf('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $obj_pdf->SetCreator(PDF_CREATOR);
        $title = "Data Invoice";
        $obj_pdf->SetTitle($title);
        if($data["use_header"]) {
            $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
            $obj_pdf->setFooterVisible(TRUE);
        }
        $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $obj_pdf->SetDefaultMonospacedFont('helvetica');
        $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $obj_pdf->SetFont('times', '', 10);
        $obj_pdf->setFontSubsetting(false);
        $obj_pdf->AddPage();
        $content = $this->load->view("transaksi/view_invoice_print", $data, true);
        $obj_pdf->writeHTML($content, true, false, true, false, '');
        $obj_pdf->Output('invoice-'.$kode.'.pdf', 'I');
    }

    public function invoice_export($jenis_invoice = "") {
        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("i.nomor_invoice", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Invoice", "To", "Nama Vessel");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/invoice", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(i.tanggal_invoice) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        if ($jenis_invoice != ""){
            $where .= " and i.is_final = ".$jenis_invoice;
        }
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $queryExport = "SELECT i.nomor_invoice, i.tanggal_invoice, p.nomor_po, i.using_dollar_currency, i.list_dn_id, i.tambahkan_ppn,
                i.penerbit_invoice, i.submitter, i.date_submit,
                c.nama_customer, c.kota_customer, c.alamat_customer, c.alamat_detail_customer, c.kode_pos_customer,
                c.telepon_customer, c.fax_customer, c.email_customer, c.attendance
                FROM data_invoice_to_cust i
                LEFT JOIN data_po_from_customer p ON i.id_po = p.id_po
                LEFT JOIN master_customer c ON p.id_customer = c.id_customer
                $where";
        $this->export($queryExport);
    }

    /**
     * DELIVERY NOTE
     */

    public function delivery() {
        $this->load->library("datagrid");

        $data = array();

        $this->log_event = "Membuka menu delivery note";

        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("d.nomor_purchase", "d.subject", "d.to", "q.nomor_quotation", "p.nomor_po");
        $field_title = array("Nomor Purchase", "Subjek", "To", "Nomor Quotation", "Nomor PO");
        $field_type = array("text", "text", "text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/delivery", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(d.tanggal_dn) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $offset = $this->input->get("per_page") ? $this->input->get("per_page") : 0;
        $length = 30;
        $result = $this->model_transaksi->getDeliveryData($where, $offset, $length);

        $this->datagrid->addMenu(GreyBox::createLink(base_url() . "index.php/transaksi/delivery_add/", "", "Tambah Data", "add", "onclick", 1024, 600));
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi/delivery_export/?" . $this->input->server("QUERY_STRING") . "\" class=\"report\" title=\"Export Data Purchase Order\">&nbsp;</a>");

        $rowCount = $result->num_rows();

        $this->datagrid->setActionColumnsWidth(50);
        $this->datagrid->setColumns("No.", "Nomor DN", "Tanggal", "To", "Nomor Quotation", "Nomor PO", "Location", "Submitter");
        $this->datagrid->setPaginationDataNew($this->model_transaksi->get_scalar("SELECT COUNT(*) as jml FROM data_dn_to_cust d $where", "jml"), $length, "transaksi/delivery", $rowCount, $offset);
        $this->datagrid->setButtonExportVisible(false);

        if ($rowCount > 0) {
            $nomor = $offset + 1;

            foreach ($result->result() as $row) {
                $rowID = $row->id_dn;

                $this->datagrid->addRowAction("edit('" . $rowID . "')", "edit", "Ubah Purchase");
                $this->datagrid->addRowAction("cetak('" . $rowID . "')", "resume", "Cetak Purchase");
                $this->datagrid->addRowAction("hapus('" . $rowID . "')", "delete", "Hapus Purchase");

                $this->datagrid->addRowData(
                        $nomor++, $row->nomor_dn, $row->tanggal_dn, $row->to, $row->nomor_quotation, $row->id_invoice ? $row->id_invoice : "-", $row->location, $row->submitter
                );
            }
        }
        else {
            $this->datagrid->setEmptyDataState("Tidak ada data");
        }

        $data['breadcrumb'] = $this->breadCrumb(true);
        $data['date_picker'] = new jDatePicker();
        $data['filter_panel'] = $filter_panel;

        $this->loadMenu('transaksi/delivery', $data);
    }

    public function delivery_add($kode = -1, $id_invoice = "") {
        $data = array();

        if($this->input->post("btnSubmit")) {
            $vars = array(
                    "nomor_dn" => "",
                    "tanggal_dn" => date("Y-m-d"),
                    "to" => "",
                    "rf_number" => "",
                    "delivery_to" => "",
                    "location" => "",
                    "subject" => "",
                    "id_item" => array(),
                    "quantity" => array(),
                    "checked_by" => "",
                    "delivered_by" => "",
                    "received_by" => "",
                    "received_by_2" => "",
                    "btnSubmit" => "Save"
            );

            $data = array();
            retrieve_request($data, $vars);
            $data["submitter"] = $this->userauth->getNik();
            $data["date_submit"] = date("Y-m-d H:i:s");


            if(count($data["id_item"]) < 1)
                $data["error"] = "Item can't be empty";
            else {
                if($kode == "" || $kode == -1)
                    $id_dn = $this->model_transaksi->insertDelivery($data, $id_invoice);
                else {
                    $id_dn = $kode;
                    $this->model_transaksi->updateDelivery($data, $id_dn, $id_invoice);
                }

                $this->model_transaksi->db->delete("data_dn_to_cust_item", "id_dn = '$id_dn'");
                foreach($data["id_item"] as $key => $id) {
                    $this->model_transaksi->insertDeliveryItem($id_dn, $id, $data["quantity"][$key]);
                }

                $data["is_success"] = 1;
                $data["kode"] = $id_dn;
            }

            if(!$data["is_success"] && count($data["id_item"]) > 0) {
                $this->load->library("dbresult_dummy");

                foreach($data["id_item"] as $key => $id) {
                    $item = $this->model_transaksi->getItem($id);
                    $this->dbresult_dummy->new_object($item);
                    $this->dbresult_dummy->assoc("quantity", $data["quantity"][$key]);
                    $this->dbresult_dummy->insert_object();
                }

                $data["item"] = $this->dbresult_dummy;
            }
        }

        $id_po = $this->input->get("po", true);
        $data["kode"] = $kode;
        $data["id_invoice"] = $id_invoice;

        if($kode != "" && $kode != -1) {
            retrieve_delivery_data($data, $kode);
        } else if($id_po != "") {
            retrieve_purchase_data($data, $id_po);
            $data["tanggal_dn"] = date("Y-m-d");
            $data["id_po"] = $id_po;
        } else {
            $data["tanggal_dn"] = date("Y-m-d");
        }

        $data["prefix"] = $this->model_transaksi->getPrefixDeliveryNo();
        $data["gbquot"] = $this->greybox->createLink(base_url() . 'index.php/transaksi/quotation/1', '<span></span>', 'Cari Quotation', 'find', '', 750, 450);
        $data['gbitem'] = $this->greybox->createLink(base_url() . 'index.php/popup/master_item', '<span>Tambah Item</span>', 'Tambah Item', 'find', '', 820, 450);

        $this->loadMenuHeaderPopup("transaksi/view_delivery_add",$data);
    }

    public function delivery_delete($kode, $id_invoice = "") {
        $this->model_transaksi->deleteDelivery($kode);
        echo "<script>alert('Data berhasil dihapus');</script>";
        if($id_invoice == "")
            echo "<script>location.href = '".  site_url("transaksi/delivery?".$_SERVER["QUERY_STRING"])."'</script>";
        else
            echo "<script>location.href = '".  site_url("transaksi/invoice_add/$id_invoice")."'</script>";
    }

    public function delivery_print($kode = "") {
        $data = array();
        retrieve_delivery_data($data, $kode);

        $this->load->library("dcpdf");

        $obj_pdf = new dcpdf('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $obj_pdf->SetCreator(PDF_CREATOR);
        $title = "Data Delivery Note";
        $obj_pdf->SetTitle($title);
        if($data["use_header"]) {
            $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
            $obj_pdf->setFooterVisible(TRUE);
        }
        $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $obj_pdf->SetDefaultMonospacedFont('helvetica');
        $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $obj_pdf->SetFont('times', '', 10);
        $obj_pdf->setFontSubsetting(false);
        $obj_pdf->AddPage();
        $content = $this->load->view("transaksi/view_delivery_print", $data, true);
        $obj_pdf->writeHTML($content, true, false, true, false, '');
        $obj_pdf->Output('dn-'.$kode.'.pdf', 'I');
    }

    public function delivery_export() {
        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("d.nomor_purchase", "d.subject", "q.nomor_quotation", "p.nomor_po");
        $field_title = array("Nomor Purchase", "Subjek", "To", "Nomor Quotation", "Nomor PO");
        $field_type = array("text", "text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi/delivery", $field_name, $field_title, $field_type);
        if($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(d.tanggal_dn) BETWEEN '".$data['srcPeriodStart']."' AND '".$data['srcPeriodEnd']."' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $queryExport = "SELECT d.tanggal_dn, d.nomor_dn, d.to, d.rf_number, d.delivery_to, d.location, d.subject, d.submitter, d.date_submit,
                        d.checked_by, d.delivered_by, d.received_by, d.received_by_2, q.nomor_quotation, i.nomor_invoice
                        FROM data_dn_to_cust d
                        LEFT JOIN data_quotation_to_cust q ON d.quotation_id = q.id_quotation
                        LEFT JOIN data_invoice_to_cust i ON d.id_invoice = i.id_invoice
                $where ";
        $this->export($queryExport);
    }

}

?>
